package com.example.nettydemo.simple;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.concurrent.*;

/**
 * Netty Server 启动类，基于Spring
 *
 * @author SuperWein
 */
@Slf4j
@Component
public class NettyServerStartup {
    // 连接池
    private ExecutorService executorService;

    @Value("${netty.server.port}")
    private int port;
    @Value("${netty.server.read-timeout}")
    private long readIdelTimeOut;
    @Value("${netty.server.write-timeout}")
    private long writeIdelTimeOut;
    @Value("${netty.server.all-timeout}")
    private long allIdelTimeOut;
    @Value("${netty.server.messagesize.max}")
    private int messageMaxSize;

    /**
     * bean初始化，IoC容器中的Bean依赖注入完成之后调用
     */
    @PostConstruct
    public void init() {
        //  创建连接池，长度固定
        executorService = new ThreadPoolExecutor(1, 1,
                0L, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<Runnable>());

        executorService.submit(new Runnable() {
            @Override
            public void run() {
                try {
                    // 启动 Netty Server 服务端
                    new NettyServer().readIdelTimeOut(readIdelTimeOut).writeIdelTimeOut(writeIdelTimeOut)
                            .allIdelTimeOut(allIdelTimeOut).messageMaxSize(messageMaxSize).bind(port).start();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 在bean销毁之前调用
     */
    @PreDestroy
    public void destroy() {
        // 关闭连接池
        executorService.shutdown();
    }

}
